package hongcaosp.app.android.video.online;

import android.content.Intent;
import android.media.MediaPlayer;
import android.os.Environment;
import android.support.annotation.NonNull;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.gcssloop.widget.PagerGridLayoutManager;
import com.gcssloop.widget.PagerGridSnapHelper;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import hongcaosp.app.android.R;
import hongcaosp.app.android.common.BaseAdapter;
import hongcaosp.app.android.common.BaseHolder;
import hongcaosp.app.android.video.online.bean.OnlineMusic;
import hongcaosp.app.android.video.online.bean.OnlineRank;
import hongcaosp.app.android.video.online.bean.OnlineType;
import hongcaosp.app.android.video.online.holder.OnlineMusicHolder;
import hongcaosp.app.android.video.online.holder.OnlineRankHolder;
import hongcaosp.app.android.video.online.holder.OnlineTypeHolder;
import hongcaosp.app.android.video.online.iview.IOnlineHomeView;
import hongcaosp.app.android.video.online.presenter.OnlineHomePresenter;
import xlj.lib.android.base.component.BaseActivity;
import xlj.lib.android.base.toastcompat.ToastManager;
import xlj.lib.android.base.view.OnRecycleItemClickListener;

public class OnLineHomeActivity extends BaseActivity implements IOnlineHomeView {

    private OnlineHomePresenter presenter;

    private EditText et_search;
    private ImageView iv_clear;
    private TextView tv_search;

    private List<OnlineType> typeList = new ArrayList<>();
    private BaseAdapter<OnlineType> adapter;
    private RecyclerView rv_type;

    private BaseAdapter<OnlineRank> adapterRank;
    private RecyclerView rv_rank;

    private OnlineMusic onlineMusic;
    private DialogMusicDownload dialogMusicDownload;

    @Override
    protected void initData(final Intent intent) {

        typeList.add(new OnlineType(1,"热歌",R.drawable.online_hot));
        typeList.add(new OnlineType(2,"新歌",R.drawable.online_new));
        typeList.add(new OnlineType(3,"流行",R.drawable.online_common));
        typeList.add(new OnlineType(4,"古风",R.drawable.online_ancients));
        typeList.add(new OnlineType(5,"怀旧经典",R.drawable.online_reminiscence));
        typeList.add(new OnlineType(6,"民谣",R.drawable.online_ballad));
        typeList.add(new OnlineType(7,"纯音乐",R.drawable.online_music));
        typeList.add(new OnlineType(8,"古典音乐",R.drawable.online_classical));

        rv_type.setLayoutManager(new PagerGridLayoutManager(2,4,PagerGridLayoutManager.HORIZONTAL));
        PagerGridSnapHelper snapHelper = new PagerGridSnapHelper();
        snapHelper.attachToRecyclerView(rv_type);
        rv_type.setAdapter(adapter = new BaseAdapter<OnlineType>() {
            @NonNull
            @Override
            public BaseHolder<OnlineType> onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
                return new OnlineTypeHolder(LayoutInflater.from(OnLineHomeActivity.this).inflate(R.layout.item_online_type, parent, false), new OnRecycleItemClickListener() {
                    @Override
                    public void onItemClick(int position) {
                        Intent intent1 = new Intent(OnLineHomeActivity.this,OnLineCategoryActivity.class);
                        intent1.putExtra("id",typeList.get(position).getId());
                        intent1.putExtra("title",typeList.get(position).getTitle());
                        startActivityForResult(intent1,999);
                    }

                    @Override
                    public void onItemLongClick(int position) {

                    }
                });
            }
        });
        adapter.setData(typeList);
        adapter.notifyDataSetChanged();


        presenter.list();
    }

    @Override
    protected void initView() {
        presenter = new OnlineHomePresenter(this);
        findViewById(R.id.back).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onBackPressed();
            }
        });
        et_search = findViewById(R.id.et_search);
        iv_clear = findViewById(R.id.iv_clear);
        tv_search = findViewById(R.id.tv_search);
        rv_type = findViewById(R.id.rv_type);
        rv_rank = findViewById(R.id.rv_rank);

        et_search.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                iv_clear.setVisibility(s.length() > 0 ? View.VISIBLE : View.GONE);
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
        iv_clear.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                et_search.setText("");
            }
        });
        tv_search.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String content = et_search.getText().toString().trim();
                if (TextUtils.isEmpty(content)) {
                    return;
                }
                Intent intent = new Intent(OnLineHomeActivity.this,OnLineCategoryActivity.class);
                intent.putExtra("content",content);
                startActivityForResult(intent,999);
            }
        });
    }

    @Override
    protected int getLayoutRes() {
        return R.layout.activity_online_home;
    }

    @Override
    public void rankData(List<OnlineRank> rankList) {
        rv_rank.setLayoutManager(new LinearLayoutManager(this));
        rv_rank.setAdapter(adapterRank = new BaseAdapter<OnlineRank>() {
            @NonNull
            @Override
            public BaseHolder<OnlineRank> onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
                return new OnlineRankHolder(LayoutInflater.from(OnLineHomeActivity.this).inflate(R.layout.item_online_rank, parent, false),OnLineHomeActivity.this, new OnlineMusicHolder.IOnItemClickListener() {
                    @Override
                    public void onItemClick(final OnlineMusic music) {
                        if (onlineMusic != null) {
//                            if (onlineMusic.getId().equals(music.getId())) {
//                                changePlayStatus(onlineMusic.getStatus() != 0 ? 0 : 2);
//                                rv_rank.post(new Runnable() {
//                                    @Override
//                                    public void run() {
//                                        VoiceUtil.toggle();
//                                    }
//                                });
//                                return;
//                            }
                            playOver();
                        }
                        onlineMusic = music;
                        changePlayStatus(1);
                        rv_rank.post(new Runnable() {
                            @Override
                            public void run() {
                                try {
                                    File rootFile = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/redgrass/txvodcache/music");
                                    if (!rootFile.exists()) {
                                        rootFile.mkdirs();
                                    }
                                    File musicFile = new File(rootFile,onlineMusic.getId() + ".mp3");
                                    if (musicFile.exists()) {
                                        VoiceUtil.play(OnLineHomeActivity.this,musicFile,onPreparedListener,onCompletionListener,onErrorListener);
                                    } else {
                                        VoiceUtil.play(onlineMusic.getSongUrl(),onPreparedListener,onCompletionListener,onErrorListener);
                                    }
                                } catch (IOException e) {
                                    e.printStackTrace();
                                    runOnUiThread(new Runnable() {
                                        @Override
                                        public void run() {
                                            ToastManager.getInstance().showToast("播放错误");
                                            playOver();
                                        }
                                    });
                                }
                            }
                        });
                    }

                    @Override
                    public void onUseClick(OnlineMusic music) {
                        // 使用
                        if (dialogMusicDownload == null) {
                            dialogMusicDownload = new DialogMusicDownload(OnLineHomeActivity.this, new DialogMusicDownload.IOnDownloadListener() {
                                @Override
                                public void onOver(String filePath) {
                                    Intent intent = new Intent();
                                    intent.putExtra("path", filePath);
                                    setResult(RESULT_OK, intent);
                                    finish();
                                }
                            });
                        }
                        dialogMusicDownload.download(music);
                    }
                });
            }
        });
        adapterRank.setData(rankList);
        adapterRank.notifyDataSetChanged();
    }

    @Override
    protected void onPause() {
        super.onPause();
        VoiceUtil.release();
        changePlayStatus(0);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == RESULT_OK && requestCode == 999) {
            setResult(RESULT_OK, data);
            finish();
        }
    }

    private MediaPlayer.OnPreparedListener onPreparedListener = new MediaPlayer.OnPreparedListener() {
        @Override
        public void onPrepared(MediaPlayer mp) {
            // 准备完成
            changePlayStatus(2);
        }
    };

    private MediaPlayer.OnCompletionListener onCompletionListener = new MediaPlayer.OnCompletionListener() {
        @Override
        public void onCompletion(MediaPlayer mp) {
            // 播放完成
            playOver();
        }
    };

    private MediaPlayer.OnErrorListener onErrorListener = new MediaPlayer.OnErrorListener() {
        @Override
        public boolean onError(MediaPlayer mp, int what, int extra) {
            // 播放出错
            ToastManager.getInstance().showToast("播放错误");
            playOver();
            return false;
        }
    };

    private void changePlayStatus(int status) {
        if (onlineMusic != null) {
            onlineMusic.setStatus(status);
            adapterRank.notifyDataSetChanged();
        }
    }

    private void playOver() {
        if (onlineMusic != null) {
            onlineMusic.setStatus(0);
            adapterRank.notifyDataSetChanged();
        }
        rv_rank.post(new Runnable() {
            @Override
            public void run() {
                VoiceUtil.release();
            }
        });
    }
}
